package controller;

import com.google.gson.Gson;
import entry.User;
import service.UserService;
import service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
@SuppressWarnings("all")
@WebServlet("/UserServlet/*")
public class UserServlet extends HttpServlet {

    private UserService userService=new UserServiceImpl();

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //0、处理乱码
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");

        //1.获得请求路径
        String url = request.getRequestURI();
        String methodName = url.substring(url.lastIndexOf("/")+1);
        Class cla = UserServlet.class;
        try {
            Method method = cla.getMethod(methodName,HttpServletRequest.class,HttpServletResponse.class);
            method.invoke(cla.newInstance(),request,response);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    public void login(HttpServletRequest request, HttpServletResponse response) throws IOException {

        String account = request.getParameter("account");
        String password = request.getParameter("password");
        System.out.println(account);

        User user=new User();
        user.setAccount(account);
        user.setPassword(password);

        boolean b = userService.login(user);
        String userName = userService.selectUserByName(account).getName();


        // 创建一个 cookie
        Cookie cookie = new Cookie("username",userName);

        // 设置 cookie 的最大生存时间
        cookie.setMaxAge(60 * 60 * 24); // 设置为一天

        // 添加到响应头
        response.addCookie(cookie);

        Gson gson=new Gson();
        response.getWriter().println(gson.toJson(b));

    }
}